package com.gandong8.tablestore.tool.config;

import com.alicloud.openservices.tablestore.SyncClient;
import com.alicloud.openservices.tablestore.TunnelClient;
import com.gandong8.tablestore.tool.config.properties.TableStoreProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(TableStoreProperties.class)
@Slf4j
public class TableStoreConf {

    @Autowired
    private TableStoreProperties tableStoreProperties;

    @Bean(destroyMethod = "shutdown")
    @ConditionalOnMissingBean(SyncClient.class)
    public SyncClient syncClient() {
        return createResource();
    }
    @Bean
    public TunnelClient tunnelClient() {
        try {
            return new TunnelClient(tableStoreProperties.getEndpoint(), tableStoreProperties.getAccessKeyId(), tableStoreProperties.getAccessKeySecret(), tableStoreProperties.getInstanceName());
        } catch (Exception e) {
            log.error("TunnelClientFailed", e);
            return null;
        }
    }

    private SyncClient createResource() {
        return new SyncClient(tableStoreProperties.getEndpoint(), tableStoreProperties.getAccessKeyId(), tableStoreProperties.getAccessKeySecret(), tableStoreProperties.getInstanceName());
    }

}
